package com.yao.spider.yiyao;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.yao.spider.core.util.MyBatiesUtils;
import com.yao.spider.yiyao.bean.MedicineInfoStandard;
import com.yao.spider.yiyao.bean.YaoZhWang;
import com.yao.spider.yiyao.dao.*;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.ibatis.session.SqlSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class YaozhRequest {
    public static void smDetail() {
        SqlSession sqlSession = MyBatiesUtils.getSqlSession();
        MedicineInfoStandardDao medicineInfoStandardDao = new MedicineInfoStandardDaoImpl();
        List<MedicineInfoStandard> medicineInfoStandards = medicineInfoStandardDao.selectShiYzNullAll(sqlSession);
        YaoZhWangDao yaoZhWangDao = new YaoZhWangDaoImpl();
        for (MedicineInfoStandard standard : medicineInfoStandards) {
            final OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .headers(Headers.of(HttpUtil.buildYaoZhHeaderMap()))
                    .url("https://db.yaozh.com/pijian?comprehensivesearchcontent=" +  URLEncoder.encode(standard.getApplyNo()))
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                } else {
                    String resPage = response.body().string();
//                    System.out.println(resPage);
                    Document parse = Jsoup.parse(resPage);
                    Elements allSm = parse.select("tbody");
                    Element element1 = allSm.get(0);
                    Elements hrefA = element1.select("a");
                    String href = hrefA.get(0).attr("href");
                    YaoZhWang yaoZhWang = new YaoZhWang();
                    yaoZhWang.setApplyNo(standard.getApplyNo());
                    yaoZhWang.setMedicineName(standard.getMedicineName());
                    yaoZhWang.setMedicineUrl(href);
                    yaoZhWangDao.insert(yaoZhWang, sqlSession);
                    System.out.println(yaoZhWang.toString());
                    System.out.println(href);
                    Thread.sleep(10000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        smDetail();
        String encode = URLEncoder.encode("国药准字H31021720");
        System.out.println(encode);

    }
//    　按国家规定，化学制剂等西药产品均需在其说明书或标签上注明“适应症”，中药产品（主要是成药）需在其说明书标签上注明“功能与主治”。

}
